package com.lemote.dao.schedule.impl;

import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.scheduling.annotation.Async;

import com.lemote.core.Page;
import com.lemote.dao.schedule.WorkScheduleDao;
import com.lemote.entity.ScheuleEntity;
import com.lemote.utils.DataUtils;
import com.lemote.utils.encode.EncodeUtils;

/**
 * 
 * @author slaton
 * @time 2011-7-12 下午07:54:15
 * @Version:0.0.1
 * @since smt
 */

public class WorkScheduleDaoImpl implements WorkScheduleDao {

	private String username;

	private String password;

	private String path;

	private String databaseName;

	@Async
	@Override
	public void backup() {
		try {
			DataUtils.backup(username, password, path, databaseName);
		} catch (IOException e) {
			System.out.println("back error");
		}
	}

	@Override
	public void recove(File file) {
		DataUtils.recove(username, password, file, databaseName);
	}

	@Override
	public Page<ScheuleEntity> fileList(Page page) {
		return changeScheuleEntity(page);
	}

	public Page<ScheuleEntity> changeScheuleEntity(Page page) {
		List<ScheuleEntity> ses = new ArrayList<ScheuleEntity>();
		List<File> files = DataUtils.fileList(new File(path));
		if (files != null) {
			Collections.reverse(files);
			for (File file : files) {
				if (file.exists() && file.isFile()) {
					ScheuleEntity se = new ScheuleEntity();
					se.setCreateTime(new Date(file.lastModified()));
					se.setFileName(file.getAbsolutePath());
					se.setId(EncodeUtils.base64Encode((file.getAbsolutePath())
							.getBytes()));
					ses.add(se);
				}
			}
		}
		Integer total = ses.size();
		Integer pageindex = (page.getPageNo() - 1) * page.getPageSize();
		Integer pagesize = page.getPageSize();
		if (total > pageindex) {
			if (total > pagesize) {
				page.setResult(ses.subList(pageindex, pagesize));
			} else {
				page.setResult(ses.subList(pageindex, total));
			}
		}

		page.setTotalCount(ses.size());

		return page;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public void setDatabaseName(String databaseName) {
		this.databaseName = databaseName;
	}


}
